package com.aaa.sercurity;

import com.aaa.dao.F_userDao;
import com.aaa.dao.UserDao;
import com.aaa.entity.F_user;
import com.aaa.entity.ResultCode;
import com.aaa.entity.SecurityUser;
import com.aaa.entity.User;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Component
public class UserDetailsConfig implements UserDetailsService {
    public  String  a;
    public String cid;
    @Resource
    UserDao userDao;

    @Resource
    F_userDao f_userDao;

    @Resource
    private HttpServletRequest request;

    @Resource
    SecurityConfig securityConfig;
    /**
     * 根据用户名获取用户详细信息
     *
     * @param name
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String name) {
        System.out.println("用户名：" + name);
        // 查询数据库
        a=name;
        String clientId = request.getParameter("client_id");
        cid=clientId;
        System.out.println(clientId);
        SecurityUser securityUser = null;
        if (clientId.equals("vueback")) {
            List<User> list = userDao.selectByUname(name);
            if (list.size() == 1) {
                User user = list.get(0);
                securityUser = new SecurityUser(user.getUsername(), user.getPassword(), user.getState() == 0, "vueback");
            }
        } else if (clientId.equals("vuefront")) {
            List<F_user> list = f_userDao.selectByUname(name);
            if (list.size() == 1) {
                F_user f_user = list.get(0);
                System.out.println("这是我查出的username"+f_user.getUsername());
                securityUser = new SecurityUser(f_user.getUsername(), f_user.getPassword(), f_user.getState() == 0, "vuefront");
            }
        }
        if (securityUser != null) {
            if (securityUser.isEnabled()){
              return securityUser;
            }else {
                throw new DisabledException(ResultCode.NO_DISABLED.getMsg());
            }
        } else {
            throw new UsernameNotFoundException("用户名不存在");
        }
    }
}
